<template>
  <div class="manage-container">
    <div class="page-header">
      <h2>展演管理</h2>
        <div v-if="mainStore.userInfo.role.roleType >= 80">
          <el-button type="primary" @click="handleAdd" >新增展演</el-button>
          <el-button type="primary" @click="exportActivityList(searchForm)" :disabled="!tableData.length">导出明细</el-button>
      </div>
    </div>
    <div class="page-content">
      <!-- 搜索表单 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="机构">
          <el-select
            v-model="searchForm.organizationId"
            placeholder="请选择机构"
            clearable
            :disabled="organizationOptions.length === 1">
            <el-option
              v-for="org in organizationOptions"
              :key="org.id"
              :label="org.username"
              :value="org.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.name" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="searchForm.performanceTime"
            type="datetime"
            placeholder="请选择活动时间"
            clearable />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.activityStatus" placeholder="请选择状态" clearable>
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="ended" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格容器 -->
      <div class="table-container">
        <el-table :data="tableData" border style="width: 100%" height="600px">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="活动名称" min-width="100" />
          <el-table-column prop="performanceTime" label="活动时间" width="150">
            <template #default="scope">
              {{ formatDateTime(scope.row.performanceTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="registrationDeadline" label="报名截止" width="150">
            <template #default="scope">
              {{ formatDateTime(scope.row.registrationDeadline) }}
            </template>
          </el-table-column>
          <el-table-column label="活动地点" min-width="160">
            <template #default="scope">
              {{ `${scope.row.province}${scope.row.city}${scope.row.district}` }}
            </template>
          </el-table-column>
          <el-table-column prop="registrationCount" label="已报名人数" width="100" align="center" />
          <el-table-column label="创建者" width="100">
            <template #default="scope">
              {{ scope.row.creator?.username }}
            </template>
          </el-table-column>
          <el-table-column label="活动状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.statusText)">
                {{ scope.row.statusText }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="390" fixed="right">
            <template #default="scope">
              <div class="text-center">
              <el-button type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button
                type="primary"
                @click="handleEdit(scope.row)"
                v-if="mainStore.userInfo.role.roleType >= 80"
                >编辑</el-button
              >
              <el-button
                type="danger"
                @click="handleDelete(scope.row)"
                v-if="mainStore.userInfo.role.roleType >= 80">
                删除
              </el-button>
              <el-button type="primary" @click="handleRegistration(scope.row)">报名表</el-button>
              <el-button type="success" @click="copyRegistrationLink(scope.row)"
                >报名链接</el-button
              >
            </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增展演' : '编辑展演'"
      width="600px">
      <el-form :model="performanceForm" label-width="100px">
        <el-form-item label="活动机构" required>
          <el-select
            v-model="performanceForm.organizationId"
            placeholder="请选择活动机构"
            :disabled="organizationOptions.length === 1"
            style="width: 100%">
            <el-option
              v-for="org in organizationOptions"
              :key="org.id"
              :label="org.username"
              :value="org.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称" required>
          <el-input v-model="performanceForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动时间" required>
          <el-date-picker
            v-model="performanceForm.performanceTime"
            type="datetime"
            placeholder="请选择活动时间"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="报名截止" required>
          <el-date-picker
            v-model="performanceForm.registrationDeadline"
            type="datetime"
            placeholder="请选择报名截止时间"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="所在地区" required>
          <div class="area-select">
            <el-select
              v-model="performanceForm.province"
              placeholder="请选择省份"
              @change="handleProvinceChange">
              <el-option
                v-for="item in areaOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label" />
            </el-select>
            <el-select
              v-model="performanceForm.city"
              placeholder="请选择城市"
              :disabled="!performanceForm.province"
              @change="handleCityChange">
              <el-option
                v-for="item in cityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label" />
            </el-select>
            <el-select
              v-model="performanceForm.district"
              placeholder="请选择区县"
              :disabled="!performanceForm.city">
              <el-option
                v-for="item in districtOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="详细地址" required>
          <el-input v-model="performanceForm.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="活动图片">
          <el-upload
            class="image-upload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            accept="image/*">
            <div v-if="performanceForm.image" class="image-preview">
              <img :src="imgUrls(performanceForm.image)" class="preview-image" />
              <div class="image-preview-mask">
                <el-icon class="preview-icon"><Plus /></el-icon>
              </div>
            </div>
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="performanceForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="展演详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="活动机构">
          {{
            organizationOptions.find((org) => org.id === currentPerformance?.organizationId)
              ?.username
          }}
        </el-descriptions-item>
        <el-descriptions-item label="活动名称">{{ currentPerformance?.name }}</el-descriptions-item>
        <el-descriptions-item label="活动时间">{{
          formatDateTime(currentPerformance?.performanceTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="报名截止">{{
          formatDateTime(currentPerformance?.registrationDeadline)
        }}</el-descriptions-item>
        <el-descriptions-item label="所在地区">
          {{
            `${currentPerformance?.province}${currentPerformance?.city}${currentPerformance?.district}`
          }}
        </el-descriptions-item>
        <el-descriptions-item label="详细地址">{{
          currentPerformance?.address
        }}</el-descriptions-item>
        <el-descriptions-item label="已报名人数">{{
          currentPerformance?.registrationCount || 0
        }}</el-descriptions-item>
        <el-descriptions-item label="活动状态">
          <el-tag :type="getStatusTagType(currentPerformance?.statusText)">
            {{ currentPerformance?.statusText }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="活动图片" :span="2">
          <el-image
            v-if="currentPerformance?.image"
            :src="imgUrls(currentPerformance.image)"
            style="width: 178px; height: 178px; object-fit: cover" />
          <span v-else>暂无图片</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ currentPerformance?.remarks || '无' }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, computed } from 'vue';

  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import Http from '@/utils/http';
  import { areaOptions } from '@/utils/area-data';
  import OSS from 'ali-oss';
  import { exportActivityList } from '@/utils/Api';
  import { imgUrls } from '@/utils/utils';
  import { useMainStore } from '@/stores/useMain';

  const mainStore = useMainStore();


  const client = new OSS({
    region: 'oss-cn-chengdu',
    accessKeyId: 'LTAI5t8ySspV3RByRTKBdHdF',
    accessKeySecret: 'SalGEBIs14QFqZ7dmKnHvFquxtGBAh',
    bucket: 'yipei001',
    secure: true, // 使用 HTTPS
    endpoint: 'oss-cn-chengdu.aliyuncs.com', // 指定 endpoint
  });

  // 修改 OSS 客户端配置
  // const client = new OSS({
  //   region: 'oss-cn-chengdu',
  //   accessKeyId: 'LTAI5t6pEr2wMKtDAfWSwo1H',
  //   accessKeySecret: 'Nrn34ANQF6Dqi5Koo23jd2ljJadWq1',
  //   bucket: 'yipei',
  //   secure: true, // 使用 HTTPS
  //   endpoint: 'oss-cn-chengdu.aliyuncs.com', // 指定 endpoint
  // });

  // 机构选项
  const organizationOptions = ref([]);

  // 修改搜索表单数据结构
  const searchForm = reactive({
    organizationId: '',
    name: '',
    performanceTime: '',
    activityStatus: '',
  });

  // 表格数据
  const tableData = ref([]);
  const total = ref(0);
  const currentPage = ref(1);
  const pageSize = ref(10);

  // 对话框相关
  const dialogVisible = ref(false);
  const detailDialogVisible = ref(false);
  const dialogType = ref('add');
  const performanceForm = reactive({
    organizationId: '',
    name: '',
    performanceTime: '',
    registrationDeadline: '',
    province: '',
    city: '',
    district: '',
    address: '',
    image: '',
    remarks: '',
  });
  const currentPerformance = ref(null);

  // 地区选择相关
  const cityOptions = ref([]);
  const districtOptions = ref([]);

  // 页面加载时获取数据
  onMounted(() => {
    getOrganizations();
    getActivityList();
  });
  // 获取机构列表
  const getOrganizations = async () => {
    try {
      const res = await Http.get({
        url: '/yp_admin/getSubuser',
      });
      organizationOptions.value = res.data.list || [];

      // 如果只有一条数据，自动选中且不可修改
      if (organizationOptions.value.length === 1) {
        searchForm.organizationId = organizationOptions.value[0].id;
        getActivityList(); // 自动加载数据
      }
    } catch (error) {
      console.error('获取机构列表失败:', error);
    }
  };

  // 获取活动列表
  const getActivityList = async () => {
    try {
      const params = {
        ...searchForm,
        page: currentPage.value,
        pageSize: pageSize.value,
        performanceTime: searchForm.performanceTime
          ? new Date(searchForm.performanceTime).toISOString()
          : '',
      };

      const res = await Http.get({
        url: '/yp_admin/getActivityList',
        params,
      });
      if (res.data) {
        tableData.value = res.data.list || [];
        total.value = res.data.total || 0;
      }
    } catch (error) {
      console.error('获取活动列表失败:', error);
      ElMessage.error('获取活动列表失败');
    }
  };

  // 修改搜索方法
  const handleSearch = () => {
    currentPage.value = 1;
    getActivityList();
  };

  // 修改重置方法
  const resetForm = () => {
    // 如果只有一个机构，保持机构ID不变
    const keepOrganizationId =
      organizationOptions.value.length === 1 ? searchForm.organizationId : '';

    // 重置表单
    Object.assign(searchForm, {
      organizationId: keepOrganizationId, // 保持或清空机构ID
      name: '',
      performanceTime: '',
      activityStatus: '',
    });

    handleSearch();
  };

  // 修改分页方法
  const handleSizeChange = (val) => {
    pageSize.value = val;
    getActivityList();
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    getActivityList();
  };

  const getStatusType = (status) => {
    const map = {
      pending: 'info',
      registering: 'success',
      finished: 'warning',
    };
    return map[status];
  };

  const getStatusText = (status) => {
    const map = {
      pending: '未开始',
      registering: '报名中',
      finished: '已结束',
    };
    return map[status];
  };

  const handleAdd = () => {
    dialogType.value = 'add';
    Object.assign(performanceForm, {
      organizationId: organizationOptions.value.length === 1 ? organizationOptions.value[0].id : '',
      name: '',
      performanceTime: '',
      registrationDeadline: '',
      province: '',
      city: '',
      district: '',
      address: '',
      image: '',
      remarks: '',
      provinceText: '',
      cityText: '',
      districtText: '',
    });
    dialogVisible.value = true;
  };

  const handleEdit = (row) => {
    dialogType.value = 'edit';
    Object.assign(performanceForm, {
      ...row,
      organizationId:
        row.organizationId ||
        (organizationOptions.value.length === 1 ? organizationOptions.value[0].id : ''),
    });
    dialogVisible.value = true;
  };

  const handleView = (row) => {
    currentPerformance.value = row;
    detailDialogVisible.value = true;
  };

  const handleDelete = (row) => {
    ElMessageBox.confirm(`确定删除展演"${row.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await Http.post({
            url: '/yp_admin/deleteActivity',
            data: {
              id: row.id,
            },
          });

          if (res.code === 200) {
            ElMessage.success('删除成功');
            getActivityList(); // 刷新列表
          } else {
            ElMessage.error(res.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除活动失败:', error);
          ElMessage.error('删除失败');
        }
      })
      .catch(() => {
        // 取消删除，不做任何操作
      });
  };

  const handleSave = async () => {
    try {
      // 构建请求参数
      const params = {
        ...performanceForm,
        province: performanceForm.province || '',
        city: performanceForm.city || '',
        district: performanceForm.district || '',
        creatorId: mainStore.userInfo.id,
        performanceTime: performanceForm.performanceTime
          ? new Date(performanceForm.performanceTime).toISOString()
          : '',
        registrationDeadline: performanceForm.registrationDeadline
          ? new Date(performanceForm.registrationDeadline).toISOString()
          : '',
      };

      // 根据 dialogType 判断使用哪个接口
      const url = dialogType.value === 'add' ? '/yp_admin/addActivity' : '/yp_admin/editActivity';

      // 发送请求
      const res = await Http.post({
        url,
        data: params,
      });

      if (res.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功');
        dialogVisible.value = false;
        getActivityList(); // 刷新列表
      } else {
        ElMessage.error(res.msg || (dialogType.value === 'add' ? '添加失败' : '编辑失败'));
      }
    } catch (error) {
      console.error(dialogType.value === 'add' ? '添加活动失败:' : '编辑活动失败:', error);
      ElMessage.error(dialogType.value === 'add' ? '添加失败' : '编辑失败');
    }
  };

  // 添加日期格式化函数
  const formatDateTime = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      })
      .replace(/\//g, '-');
  };

  // 修改报名表处理函数
  const handleRegistration = async (row) => {
    try {
      const res = await Http.post({
        url: '/yp_admin/getentryform',
        data: {
          registrationId: row.id,
        },
      });

      if (res.code === 200 && res.data) {
        // 获取完整的文件URL
        const fileUrl = imgUrls(res.data);

        // 创建一个临时的a标签来触发下载
        const link = document.createElement('a');
        link.href = fileUrl;
        link.download = `报名表_${row.name}.xlsx`; // 设置下载文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        ElMessage.success('报名表下载已开始');
      } else {
        ElMessage.warning('暂无报名表数据');
      }
    } catch (error) {
      console.error('获取报名表失败:', error);
      ElMessage.error('获取报名表失败');
    }
  };

  // 添加状态标签类型判断函数
  const getStatusTagType = (status) => {
    const map = {
      进行中: 'success',
      已结束: 'info',
      未开始: 'warning',
    };
    return map[status] || 'info';
  };

  const handleProvinceChange = () => {
    performanceForm.city = '';
    performanceForm.district = '';
    // 使用 label 查找省份数据
    const selectedProvince = areaOptions.find((p) => p.label === performanceForm.province);
    if (selectedProvince) {
      cityOptions.value = selectedProvince.children || [];
    }
  };

  const handleCityChange = () => {
    performanceForm.district = '';
    const selectedProvince = areaOptions.find((p) => p.label === performanceForm.province);
    const selectedCity = selectedProvince?.children?.find((c) => c.label === performanceForm.city);
    if (selectedCity) {
      districtOptions.value = selectedCity.children || [];
    }
  };

  // 图片上传相关
  const beforeImageUpload = async (file) => {
    try {
      const fileName = `images/${Date.now()}_${file.name}`;
      const result = await client.put(fileName, file);
      if (result.url) {
        performanceForm.image = '/' + fileName;
        ElMessage.success('上传成功');
      }
    } catch (error) {
      console.error('上传失败:', error);
      ElMessage.error('上传失败');
    }
    return false; // 阻止默认上传
  };

  // 添加复制报名链接方法
  const copyRegistrationLink = async (row) => {
    if (!row.registrationLink) {
      ElMessage.warning('暂无报名链接');
      return;
    }

    try {
      await navigator.clipboard.writeText(row.registrationLink);
      ElMessage.success('复制成功');
    } catch (err) {
      // 如果剪贴板API不可用，使用传统方法
      const input = document.createElement('input');
      input.value = row.registrationLink;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      ElMessage.success('复制成功');
    }
  };

  // const handleActivityList = () => {
  //   exportActivityList
  // }
</script>

<style scoped lang="scss">
  .manage-container {
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .page-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-shrink: 0;
    }

    .page-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 0;

      .search-form {
        padding-bottom: 20px;
        flex-shrink: 0;
      }

      .table-container {
        flex: 1;
        min-height: 0;

        .el-table {
          height: 100%;

          // 使用深度选择器修改表格样式
          :deep(.el-table__inner-wrapper) {
            height: 100%;
          }

          :deep(.el-table__header-wrapper) {
            flex-shrink: 0;
          }

          :deep(.el-table__body-wrapper) {
            height: calc(100% - 40px);
            overflow-y: auto;
          }

          // 固定列样式调整
          :deep(.el-table__fixed-right) {
            height: 100%;

            .el-table__fixed-header-wrapper {
              background-color: var(--el-bg-color);
            }

            .el-table__fixed-body-wrapper {
              height: calc(100% - 40px);
              overflow-y: auto;
            }
          }
        }
      }

      .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        flex-shrink: 0;
      }
    }

    .program-list {
      margin-top: 20px;
      h3 {
        margin: 10px 0;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .area-select {
    display: flex;
    gap: 10px;

    .el-select {
      width: 33.33%;
    }
  }

  .image-upload {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .upload-placeholder {
      width: 178px;
      height: 178px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .upload-icon {
        font-size: 28px;
        color: #8c939d;
      }

      .upload-text {
        color: #8c939d;
        font-size: 14px;
        margin-top: 8px;
      }
    }

    .image-preview {
      position: relative;
      width: 178px;
      height: 178px;

      .preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .image-preview-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;
        transition: var(--el-transition-duration);

        .preview-icon {
          font-size: 28px;
          color: #fff;
        }
      }

      &:hover .image-preview-mask {
        opacity: 1;
      }
    }
  }

  .el-button + .el-button {
    margin-left: 4px; /* 减小按钮之间的间距 */
  }
</style>
